package com.ruoyi.message.service;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.message.handler.WebSocketHandler;
import com.ruoyi.message.handler.WebSocketPool;
import com.ruoyi.system.domain.DzHuiyi;
import com.ruoyi.system.service.IDzHuiyiService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.javassist.expr.NewArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.stream.Collectors;

import static com.ruoyi.message.handler.WebSocketPool.*;


/**
 * @author: Zhuhongyang
 * @description: websocket服务，前端需传用户id
 * @createTime: 2023/7/17
 */
@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocketEndPoint implements ApplicationContextAware {

    public static WebSocketEndPoint webSocketEndPoint;
    private static final Logger log = LoggerFactory.getLogger(WebSocketEndPoint.class);


    private static final Set<String> FIXED_USERS = new ConcurrentSkipListSet<>();

    private static final List<MeetAdd> MEET_LIST = new ArrayList<MeetAdd>();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    private IDzHuiyiService dzHuiyiService;

    private ISysUserService userService;

    private static final Map<String, SysUser> userobjs = new ConcurrentHashMap<>();
    private static final Map<Long, DzHuiyi> meetobjs = new ConcurrentHashMap<>();

    public static final Map<String, Long> userroom = new ConcurrentHashMap<>();

    private static final Map<String, String> sharemap = new ConcurrentHashMap<>();

    private static ApplicationContext applicationContext;

    private final Map<String, Long> lastResponseTime = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        WebSocketEndPoint.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {
        webSocketEndPoint = this;
    }



    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session){

        log.info("userid========！"+username);
        log.info("session========！"+ session);
        if (session == null) {
            log.info("session信息为空！");
        } else {
            log.info("有新的连接：{}", session);
            if(username==null){
                log.info("用户信息为空！");
            }else{
                log.info("储存session！"+ session);
                add(username, session);

                if (!FIXED_USERS.contains(username)) {
                    FIXED_USERS.add(username);
                }
                meetlistMessage(new ArrayList<>(FIXED_USERS), session);
                Map<String, Session> map = WebSocketPool.sessionMap();
                Session se =    map.get(username);
                log.info("根据用户名"+username+"获取session:"+se);
                dzHuiyiService = applicationContext.getBean(IDzHuiyiService.class);
                userService = applicationContext.getBean(ISysUserService.class);

                //第一次进入系统的用户进行注册
                SysUser sysUser = userService.selectUserByUserName(username);
                if(sysUser==null){
                    sysUser = new SysUser();
                    sysUser.setUserName(username);
                    sysUser.setNickName(username);
                    sysUser.setPhonenumber("13813000001");
                    sysUser.setAvatar("/profile/avatar/userheader.png");
                    sysUser.setPassword(SecurityUtils.encryptPassword(username));
                    boolean regFlag = userService.registerUser(sysUser);
                    SysUser sysUsernew = userService.selectUserByUserName(username);
                    userobjs.put(username,sysUsernew);
                }
                userobjs.put(username,sysUser);

            }
        }
        log.info("在线人数：{}",count());
        sessionMap().keySet().forEach(item -> log.info("在线用户：{}", item));
    }



    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message,Session session, boolean last){
        if (last) {
            if (session.getUserProperties().get("msg") != null) {
                StringBuilder builder = (StringBuilder) session.getUserProperties().get("msg");
                builder.append(message);
                message = builder.toString();
                session.getUserProperties().remove("msg");
            }
        }
        else {
            if (session.getUserProperties().get("msg") != null) {
                StringBuilder builder = (StringBuilder) session.getUserProperties().get("msg");
                builder.append(message);
            }
            else {
                StringBuilder builder = new StringBuilder();
                builder.append(message);
                session.getUserProperties().put("msg", builder);
            }
            return;
        }

        try {
            //如果是心跳消息，更新对应session的接收时间
//            if ("heartbeat".equals(message)) {
//                lastResponseTime.put(session.getId(), System.currentTimeMillis());
//                return;
//            }
            MeetMessage meetMessage = objectMapper.readValue(message, MeetMessage.class);
            String type = meetMessage.getType();

            switch (type) {
                case "join":
                    handleJoin(meetMessage,session);
                    break;
                case "add":
                    handleadd(meetMessage,session);
                    break;
                case "close":
                    handleclose(meetMessage,session);
                    break;
                case "playermove":
                    handlemove(meetMessage,session);
                    break;
                case "playeranimation":
                    handleanimation(meetMessage,session);
                    break;
                case "cranemove":
                    handlecranemove(meetMessage,session);
                    break;
                case "cranepose":
                    handlecranepose(meetMessage,session);
                    break;
                case "safedistance":
                    handleSafedistance(meetMessage,session);
                    break;
                case "safetest":
                    handlesafetest(meetMessage,session);
                    break;
                case "chatformsg":
                    handleChatformsg(meetMessage,session);
                    break;
                case "chatforimage":
                    handleChatforimage(meetMessage,session);
                    break;
                case "openscreenshare":
                    handleChatforopen(meetMessage,session);
                    break;
                case "screensharedata":
                    handleChatforscreen(meetMessage,session);
                    break;
                case "instoppower":
                    handleinstoppower(meetMessage,session);
                    break;
                case "sharetexture":
                    handlesharetexture(meetMessage,session);
                    break;
                case "authority":
                    handleauthority(meetMessage,session);
                    break;
                default:
                    // Unknown message type
                    break;
            }
        } catch (Exception e) {
            log.info("e:", e);
        }


    }

    /**
     * 这里只接收屏幕共享消息
     * author 高飞
     * time   2023/12/3
     * @param message 屏幕共享消息
     * @param session 链接
     * @param last 是否是最后一帧
     */
    @OnMessage
    public void onMessage(byte[] message, Session session, boolean last) {
        String key = "bytes";
        Map<String,Object> map = session.getUserProperties();
        Object object = map.get(key);
        List<Byte> bytes = null;
        if (Objects.isNull(object)) {
            bytes = new ArrayList<>();
            map.put(key, bytes);
        }
        else {
            bytes = (List<Byte>)object;
        }
        for (byte b : message) {
            bytes.add(b);
        }

        if (last) {
            message = new byte[bytes.size()];
            for (int i = 0; i < message.length; i++) {
                message[i] = bytes.get(i);
            }
            bytes.clear();
            SpringUtils.getBean(RoomService.class).binMessage(session, message);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("username") String username, Session session){
        log.info("用户"+username+"连接关闭了！");
        userroom.remove(username);
        log.info("连接关闭： {}", session);
        remove(username);
        FIXED_USERS.remove(username);
        WebSocketPool.remove(username);
        log.info("断开后在线用户信息： {}", FIXED_USERS);
        SpringUtils.getBean(RoomService.class).leave(username, session);

        log.info("在线人数：{}",count());
        sessionMap().keySet().forEach(item -> log.info("在线用户：{}", item));
    }

    /**
     * 出现错误
     * @param session
     */
    @OnError
    public void onError(Session session, Throwable throwable){

        log.info("连接出现异常session信息： {}", session);
//        try {
//            session.close();
//        } catch (IOException e) {
//            log.error("onError Exception: {}", e.getMessage());
//        }
        log.info("连接出现异常： {}", throwable);
    }

    /**
     * 首次建立websocket连接，立即发送消息
     * @param userId
     * @param session
     */
    public void sendMessageImmediate(String userId, Session session){
        log.info("查询用户{}信息", session.getId());
    }

    private void handleJoin(MeetMessage meetMessage,Session session) {

//        MeetJion meet =  (MeetJion)meetMessage.getMsg();

        ObjectMapper mapper = new ObjectMapper();
        MeetJion meet = mapper.convertValue(meetMessage.getMsg(), MeetJion.class);
        //返回创建会议
        SysUser user = userobjs.get(meet.getJionuser());
        MeetAddJionBack mback = new MeetAddJionBack();
        mback.setRoomId(meet.getRoomId());
        mback.setCreatorId(user.getUserId());
        userroom.put(user.getUserName(),mback.getRoomId());
        mback.setRoomName(meetobjs.get(meet.getRoomId()).getHytitle());
        List<PlayerData> users = new ArrayList<>();
        for (String usertmp : FIXED_USERS) {
            Long otherRoomId = userroom.get(usertmp);
            if (otherRoomId == null) {
                continue;
            }

            if(otherRoomId.equals(meet.getRoomId())) {
                PlayerData pobj = new PlayerData();
                pobj.setId(userobjs.get(usertmp).getUserId());
                pobj.setUsername(usertmp);
                users.add(pobj);
            }
        }
        mback.setUsers(users);
        meetMessage.setMsg(mback);

        sendMessageToUserBack(meetMessage,session);

        MeetMessage meetMessage2  = new MeetMessage();
        meetMessage2.setType("joinplayer");
        PlayerData pobj2 = new PlayerData();
        pobj2.setId(user.getUserId());
        pobj2.setUsername(user.getUserName());
        meetMessage2.setMsg(pobj2);


        batchOthersMessage(user.getUserName(),meetMessage2,session);

        String token = gettoken(mback.getRoomName(),meet.getJionuser());
        if(token==null){
            createliveroom(mback.getRoomName());
            token = gettoken(mback.getRoomName(),meet.getJionuser());
        }
        MeetMessage meetMessage3  = new MeetMessage();
        meetMessage3.setType("webmsg");
        Webmsg wmsg = new Webmsg();
        wmsg.setUsername("web_"+meet.getJionuser());
        wmsg.setToken(token);
        meetMessage3.setMsg(wmsg);
        sendMessageToUser("web_"+meet.getJionuser(),meetMessage3,session);

        SpringUtils.getBean(RoomService.class).join(meet.getRoomId(), user.getUserName(), session);
    }

    private void handleadd(MeetMessage meetMessage,Session session) {
//        MeetAdd meet =  (MeetAdd)meetMessage.getMsg();

        ObjectMapper mapper = new ObjectMapper();
        MeetAdd meet = mapper.convertValue(meetMessage.getMsg(), MeetAdd.class);

        DzHuiyi huiyi = new DzHuiyi();
        huiyi.setHytitle(meet.getRoomName());
        huiyi.setUserName(meet.getCreator());
        huiyi.setState(0);
        dzHuiyiService.insertDzHuiyi(huiyi);
        meet.setRoomId(huiyi.getHyId());
        meet.setHystate("进行中");
        MEET_LIST.add(meet);
        meetobjs.put(huiyi.getHyId(),huiyi);
        createliveroom(meet.getRoomName());
        //返回创建会议
        SysUser user = userobjs.get(meet.getCreator());
        MeetAddJionBack mback = new MeetAddJionBack();
        mback.setRoomId(meet.getRoomId());
        mback.setCreatorId(user.getUserId());
        mback.setRoomName(meet.getRoomName());
        List<PlayerData> users = new ArrayList<>();
        PlayerData pobj = new PlayerData();
        pobj.setId(user.getUserId());
        pobj.setUsername(user.getUserName());
        users.add(pobj);
        userroom.put(user.getUserName(),mback.getRoomId());
        mback.setUsers(users);
        meetMessage.setMsg(mback);
        sendMessageToUserBack(meetMessage,session);
        meetlistMessage(new ArrayList<>(FIXED_USERS), session);

        String token = gettoken(meet.getRoomName(),meet.getCreator());
        if(token==null){
            createliveroom(meet.getRoomName());
            token = gettoken(meet.getRoomName(),meet.getCreator());
        }
        MeetMessage meetMessage2  = new MeetMessage();
        meetMessage2.setType("webmsg");
        Webmsg wmsg = new Webmsg();
        wmsg.setUsername("web_"+meet.getCreator());
        wmsg.setToken(token);
        meetMessage2.setMsg(wmsg);
        sendMessageToUser("web_"+meet.getCreator(),meetMessage2,session);

        SpringUtils.getBean(RoomService.class).join(meet.getRoomId(), user.getUserName(), session);
    }

    private void handlemove(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        PlayMove meet = mapper.convertValue(meetMessage.getMsg(), PlayMove.class);
//        log.info("接收到消息:"+JSON.toJSONString(meet) );
//        sendMessageToUserBackmove(meetMessage,session);
        batchOthersMessagemove(meet.getUsername(),meetMessage,session);
    }

    private void handleanimation(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Playeranimation meet = mapper.convertValue(meetMessage.getMsg(), Playeranimation.class);
//        log.info("接收到消息:"+JSON.toJSONString(meet) );
//        sendMessageToUserBackmove(meetMessage,session);
        batchOthersMessagemove(meet.getUsername(),meetMessage,session);
    }

    private void handlecranemove(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Cranemove meet = mapper.convertValue(meetMessage.getMsg(), Cranemove.class);
//        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handlecranepose(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Cranepose meet = mapper.convertValue(meetMessage.getMsg(), Cranepose.class);
//        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleSafedistance(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Safedistance meet = mapper.convertValue(meetMessage.getMsg(), Safedistance.class);
//        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleinstoppower(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Instoppower meet = mapper.convertValue(meetMessage.getMsg(), Instoppower.class);
//        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handlesafetest(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Safetest meet = mapper.convertValue(meetMessage.getMsg(), Safetest.class);
//        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleChatformsg(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Chatformsg meet = mapper.convertValue(meetMessage.getMsg(), Chatformsg.class);
        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handlesharetexture(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Sharetexture meet = mapper.convertValue(meetMessage.getMsg(), Sharetexture.class);
        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleauthority(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Authority meet = mapper.convertValue(meetMessage.getMsg(), Authority.class);
        sendMessageToUser(meet.getTarget(),meetMessage,session);
    }

    private void handleChatforimage(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Chatforimage meet = mapper.convertValue(meetMessage.getMsg(), Chatforimage.class);
        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleChatforscreen(MeetMessage meetMessage,Session session) {
        ObjectMapper mapper = new ObjectMapper();
        Screensharedata meet = mapper.convertValue(meetMessage.getMsg(), Screensharedata.class);
        sendMessageToUserBack(meetMessage,session);
        batchOthersMessage(meet.getUsername(),meetMessage,session);
    }

    private void handleChatforopen(MeetMessage meetMessage,Session session) {
        SpringUtils.getBean(RoomService.class)
                .beginScreenShare(session, meetMessage);
    }

    private void handleclose(MeetMessage meetMessage,Session session) {
//        MeetClose meet =  (MeetClose)meetMessage.getMsg();

        ObjectMapper mapper = new ObjectMapper();
        MeetClose meet = mapper.convertValue(meetMessage.getMsg(), MeetClose.class);

        Iterator<MeetAdd> iterator = MEET_LIST.iterator();
        while (iterator.hasNext()) {
            MeetAdd meetAdd = iterator.next();
            if (meetAdd.getRoomId().longValue() == meet.getRoomId().longValue()) {
                iterator.remove();
            }
        }


        meetlistMessage(new ArrayList<>(FIXED_USERS), session);
//        broadcastMessage(otherUsers, signalMessage,session);
    }


    private void meetlistMessage(List<String> users, Session session) {
        MeetMessage message  = new MeetMessage();
        message.setType("list");
        message.setMsg(MEET_LIST);

        for (String user : users) {
            sendMessageToUser(user, message,session);
        }
    }

    private void handleOffer(SignalMessage signalMessage,Session session) {
        List<String> otherUsers = FIXED_USERS.stream()
                .filter(user -> !user.equals(signalMessage.getFrom()))
                .collect(Collectors.toList());

        broadcastMessage(otherUsers, signalMessage,session);
    }

    private void handleAnswer(SignalMessage signalMessage,Session session) {
//        sendMessageToUser(signalMessage.getTo(), signalMessage,session);
    }

    private void handleCandidate(SignalMessage signalMessage,Session session) {
//        sendMessageToUser(signalMessage.getTo(), signalMessage,session);
    }

    private void broadcastMessage(List<String> users, SignalMessage message,Session session) {
//        for (String user : users) {
//            sendMessageToUser(user, message,session);
//        }
    }

    private void batchOthersMessage(String currentuser, MeetMessage message,Session session) {
        List<String> otherUsers = FIXED_USERS.stream()
                .filter(user -> !user.equals(currentuser))
                .collect(Collectors.toList());
        //当前用户
        Long roomid = userroom.get(currentuser);
        if (Objects.isNull(roomid)) {
            return;
        }

        for (String user : otherUsers) {
            Long otherRoomId = userroom.get(user);
            if (Objects.isNull(otherRoomId)) {
                continue;
            }

            if(otherRoomId.equals(roomid)){
                sendMessageToUser(user, message,session);
            }
        }
    }

    public void batchAllMessage(String username,MeetMessage message,Session session) {
        Long roomid = userroom.get(username);
        if (Objects.isNull(roomid)) {
            return;
        }

        for (String user : FIXED_USERS) {
            Long otherRoomId = userroom.get(user);
            if (Objects.isNull(otherRoomId)) {
                continue;
            }

            if(otherRoomId.equals(roomid)){
                sendMessageToUser(user, message,session);
            }
        }
    }

    private void batchOthersMessagemove(String currentuser, MeetMessage message,Session session) {
        List<String> otherUsers = FIXED_USERS.stream()
                .filter(user -> !user.equals(currentuser))
                .collect(Collectors.toList());
        Long roomid = userroom.get(currentuser);
        if (Objects.isNull(roomid)) {
            return;
        }

//        log.info("当前移动用户所在房间:" + roomid);
        for (String user : otherUsers) {
//            log.info("准备发送用户所在房间:" + userroom.get(user));
            Long otherRoomId = userroom.get(user);
            if (Objects.isNull(otherRoomId)) {
                continue;
            }

            if(otherRoomId.equals(roomid)){
                sendMessageToUser(user, message,session);
            }
        }
    }


    private void sendMessageToUser(String username, MeetMessage message,Session session) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Session> map = WebSocketPool.sessionMap();
            Session se =    map.get(username);

            if (se != null && se.isOpen()) {
                //给前端发送json消息
                String message1 = objectMapper.writeValueAsString(message);
                WebSocketHandler.sendMessage(se, message1);
            }else{
            }
//                log.info("向前端发送json消息:" + message1);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
    }


    private void sendMessageToUsermove(String username, MeetMessage message,Session session) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Session> map = WebSocketPool.sessionMap();
//            log.info("向前端发送给:" + username);
            Session se =    map.get(username);
            if (se != null && se.isOpen()) {
//
                //给前端发送json消息
                String message1 = objectMapper.writeValueAsString(message);
//                log.info("向前端发送json消息:" + message1);
                WebSocketHandler.sendMessage(se, message1);
            }else{
//                log.info(username+"session没取到:");
            }
//                log.info("向前端发送json消息:" + message1);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
    }


    private void sendMessageToUserBack(MeetMessage message,Session session) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
                //给前端发送json消息
                String message1 = objectMapper.writeValueAsString(message);
                WebSocketHandler.sendMessage(session, message1);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
    }

    private void sendMessageToUserBackmove(MeetMessage message,Session session) {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //给前端发送json消息
            String message1 = objectMapper.writeValueAsString(message);
            WebSocketHandler.sendMessage(session, message1);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
    }

    public static String createliveroom(String roomname){
//        String url = "http://127.0.0.1:7882/rtc/createRoom.htm";
//////        String url = "http://116.62.48.140:7882/rtc/createRoom.htm";
//        String str = null;
//        Map<String, String> params = new HashMap<>();
//        params.put("room_name",roomname);
//        params.put("maxParticipants","100");
//        params.put("emptyTimeout","7200");
//        try {
//            str = httpPost(url,params);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println("创建语音插件房间结果"+str);
//        return str;
        return null;
    }

    public static String gettoken(String roomname,String username){
//        String url = "http://127.0.0.1:7882/rtc/getToken.htm";
////        String url = "http://116.62.48.140:7882/rtc/getToken.htm";
//        String str = null;
//        Map<String, String> params = new HashMap<>();
//        params.put("name",username);
//        params.put("identity",username);
//        params.put("room_name",roomname);
//        try {
//            str = httpPost(url,params);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println("获取token信息："+str);
//
//        org.json.JSONObject json = new org.json.JSONObject(str);
//        int code =  json.getInt("code");
//        if(code==1){
//            String token = json.getString("data");
//            return token;
//        }else{
//            return null;
//        }

        return "123456";
    }



    public static String httpPost(String url, Map<String, String> params) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        // 添加请求参数到请求对象
        List<BasicNameValuePair> parameters = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));

        // 发送请求并获取响应
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    }

}
